﻿using HMACAuthentication.WebApi.Filters;
using YMJF_Service.Common;
using YMJF_Service.Models;
using PetaPoco;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace YMJF_Service.Controllers
{
    /// <summary>
    /// 文章
    /// </summary>
    [RoutePrefix("api/article")]
   
    public class ArticleController : ApiController
    {
        ConnectionStringMySQLDB db = new ConnectionStringMySQLDB();

        /// <summary>
        /// 获取文章列表
        /// </summary>
        /// <param name="page">页数</param>
        /// <param name="pagesize">每页行数</param>
        /// <param name="sort">排序字段</param>
        /// <param name="order">排序方式</param>
        /// <param name="code">栏目代码</param>
        /// <param name="title">标题</param>
        /// <returns></returns>
        [HttpGet]
        [Route("list")]
        [HMACAuthenticationAttribute]
        public ApiResult GetList(long page, long pagesize, string sort, string order, string code, string title)
        {
            ApiResult res = new ApiResult();
            try
            {
                string sqlwhere = "";
                if (!string.IsNullOrEmpty(code)) //ColumnCode 栏目代码
                {
                    sqlwhere += string.Format(" and ColumnCode = '{0}' ", code);
                }
                if (!string.IsNullOrEmpty(title))
                {
                    sqlwhere += string.Format(" and Title like '%{0}%' ", title);
                }
                string sqlorder = " order by " + sort + " " + order;
                Page<object> list = db.Page<object>(page, pagesize, @" select * from (  SELECT a.*, d1.ItemName as Issue FROM [dbo].[Article] a
	                                                                left join DictionaryDetail d1 on d1.DictCode ='IssueRange' and d1.ItemCode =a.IssueRange
                                                                  where a.SysDeleted = 0 " + sqlwhere + " ) t " + sqlorder);
                res.code = HttpCode.success;
                res.message = "获取成功";
                res.data = list;
            }
            catch (Exception ex)
            {
                MessageBL.Insert(new MessageBL(MessageType.Exception, "article", "获取文章列表错误：" + ex.Message));
                res.code = HttpCode.fail;
                res.message = ex.Message;
            }
            return res;
        }

        //TODO:待完善
        /// <summary>
        /// 获取文章列表（微信端）
        /// </summary>
        /// <param name="AccountID">账户ID</param>
        /// <param name="page">页数</param>
        /// <param name="pagesize">每页行数</param>
        /// <param name="code">栏目代码</param>
        /// <returns></returns>
        [HttpGet]
        [Route("list")]
        [HMACAuthenticationAttribute]
        public ApiResult GetList(string AccountID, long page, long pagesize, string code)
        {
            ApiResult res = new ApiResult();
            try
            {
                string sqlwhere = "";
                if (!Account.Exists(@" where SysDeleted = 0  and ID = @0 ", AccountID))
                {
                    res.code = HttpCode.Que_Failed;
                    res.message = "账号不存在";
                }
                else if (string.IsNullOrEmpty(code)) //ColumnCode 栏目代码
                {
                    res.code = HttpCode.Que_Failed;
                    res.message = "栏目代码必填";
                }
                else
                {
                    sqlwhere += string.Format(" and ColumnCode = '{0}' ", code);
                    string sqlorder = " order by SysCreate desc ";
                    Page<Article> list = Article.Page(page, pagesize, @" select * from ( SELECT * FROM [dbo].[Article] where SysDeleted = 0 " + sqlwhere + " ) t " + sqlorder);
                    res.code = HttpCode.success;
                    res.message = "获取成功";
                    res.data = list;
                }
            }
            catch (Exception ex)
            {
                MessageBL.Insert(new MessageBL(MessageType.Exception, "article", "获取文章列表（微信端）错误：" + ex.Message));
                res.code = HttpCode.fail;
                res.message = ex.Message;
            }
            return res;
        }


        /// <summary>
        /// 获取文章详细
        /// </summary>
        /// <param name="Id">文章ID</param>
        /// <returns></returns>
        [HttpGet]
        [Route("get")]
        public ApiResult GetArticle(string Id)
        {
            ApiResult res = new ApiResult();
            try
            {

                Article article = Article.SingleOrDefault(" where SysDeleted = 0 and ID = @0 ", Id);
                if (article != null)
                {
                    res.code = HttpCode.success;
                    res.message = "获取文章成功";
                    res.data = article;
                }
                else
                {
                    res.code = HttpCode.Que_Failed;
                    res.message = "获取文章失败";
                }

            }
            catch (Exception ex)
            {
                MessageBL.Insert(new MessageBL(MessageType.Exception, "article", "获取文章详细错误：" + ex.Message));
                res.code = HttpCode.fail;
                res.message = ex.Message;
            }
            return res;
        }


        /// <summary>
        /// 根据栏目代码获取文章
        /// </summary>
        /// <param name="code">栏目代码</param>
        /// <returns></returns>
        [HttpGet]
        [Route("getByCode")]
        public ApiResult GetArticleByColumnCode(string code)
        {
            ApiResult res = new ApiResult();
            try
            {

                Article article = Article.FirstOrDefault(" where SysDeleted = 0 and ColumnCode = @0 ", code);
                if (article != null)
                {
                    res.code = HttpCode.success;
                    res.message = "获取文章成功";
                    res.data = article;
                }
                else
                {
                    res.code = HttpCode.Que_Failed;
                    res.message = "获取文章失败";
                }

            }
            catch (Exception ex)
            {
                MessageBL.Insert(new MessageBL(MessageType.Exception, "article", "根据栏目代码获取文章错误：" + ex.Message));
                res.code = HttpCode.fail;
                res.message = ex.Message;
            }
            return res;
        }


        /// <summary>
        /// 添加文章
        /// </summary>
        /// <param name="data">文章信息</param>
        /// <returns></returns>
        [HttpPost]
        [Route("add")]
        [HMACAuthenticationAttribute]
        public ApiResult AddArticle(Article data)
        {
            ApiResult res = new ApiResult();

            try
            {
                string user = "admin";

                data.ID = Guid.NewGuid().ToString();
                data.SysCreatedBy = user;
                data.SysCreate = DateTime.Now;
                data.SysLastUpdBy = user;
                data.SysLastUpd = DateTime.Now;
                data.SysDeleted = false;
                object obj = data.Insert();
                if (obj != null)
                {

                    //添加信息提醒
                    if (!string.IsNullOrWhiteSpace(data.IssueRange))
                    {
                        string strIdentityCode = "";
                        string[] codeList = data.IssueRange.Split(',');
                        foreach (var item in codeList)
                        {
                            strIdentityCode += "'" + item + "',";
                        }
                        string sql = string.Format(@"INSERT INTO [dbo].[MessageAlert] select newid() as ID,'{0}' as ArticleID,'{1}' as ColumnCode,AccountID,getdate() as SysCreate from AccountRelation where SysDeleted=0 and IdentityCode in({2})   ", data.ID, data.ColumnCode, strIdentityCode.Remove(strIdentityCode.Length - 1));
                        int i = db.Execute(sql);
                        sendMsgToWX(data);
                    }
                    else if (!string.IsNullOrWhiteSpace(data.SpecificUser))
                    {
                        string strUser = "";
                        string[] codeList = data.SpecificUser.Split('|')[0].Split(',');
                        foreach (var item in codeList)
                        {
                            strUser += "'" + item + "',";
                        }
                        string sql = string.Format(@"INSERT INTO [dbo].[MessageAlert] select newid() as ID,'{0}' as ArticleID,'{1}' as ColumnCode,AccountID,getdate() as SysCreate from AccountRelation where SysDeleted=0 and AccountID in({2})   ", data.ID, data.ColumnCode, strUser.Remove(strUser.Length - 1));
                        int i = db.Execute(sql);
                        sendMsgToWX(data);
                    }
                    res.code = HttpCode.success;
                    res.message = "添加成功";
                    res.data = data;
                }
                else
                {
                    res.code = HttpCode.Add_Failed;
                    res.message = "添加失败";
                }

            }
            catch (Exception ex)
            {
                MessageBL.Insert(new MessageBL(MessageType.Exception, "article", "添加文章错误：" + ex.Message));
                res.code = HttpCode.fail;
                res.message = ex.Message;
            }
            return res;

        }

        /// <summary>
        /// 推送消息提醒
        /// </summary>
        /// <param name="data"></param>
        public void sendMsgToWX(Article data)
        {
             try
            {
                if (!string.IsNullOrWhiteSpace(data.IssueRange))
                {
                    string strIdentityCode = "";
                    string[] codeList = data.IssueRange.Split(',');
                    foreach (var item in codeList)
                    {
                        strIdentityCode += "'" + item + "',";
                    }
                    List<AccountRelation> list=AccountRelation.Fetch(@"where SysDeleted=0 and IdentityCode in("+strIdentityCode.Remove(strIdentityCode.Length - 1)+")  ");
                    foreach (var ar in list)
                    {
                        WXMsgController.SendWXMsgForStudent(ar.WxOpenID, data.Title, "消息提醒", "XX" + DateTime.Now.ToString("yyyyMMdd"), "-", "点击查看消息", "http://www.hongsiedu.com/HS/parent/MessageNotification/MessageNotification_detail.html?id=" + data.ID + "&AccountID=" + ar.AccountID);
                    }
                }
                else if (!string.IsNullOrWhiteSpace(data.SpecificUser))
                {
                    string strUser = "";
                    string[] codeList = data.SpecificUser.Split('|')[0].Split(',');
                    foreach (var item in codeList)
                    {
                        strUser += "'" + item + "',";
                    }
                    List<AccountRelation> list = AccountRelation.Fetch(@"where SysDeleted=0 and AccountID in("+strUser.Remove(strUser.Length - 1)+")  ");
                    foreach (var ar in list)
                    {
                        WXMsgController.SendWXMsgForStudent(ar.WxOpenID, data.Title, "消息提醒", "XX" + DateTime.Now.Date, "无", "点击查看消息", "http://www.hongsiedu.com/HS/parent/MessageNotification/MessageNotification_detail.html?id=" + data.ID + "&AccountID="+ar.AccountID);
                    }
                }

            }
             catch (Exception ex)
             {
                 MessageBL.Insert(new MessageBL(MessageType.Exception, "sendWX", "推送文章信息提醒到微信错误：" + ex.Message));
             }
 
        }


        /// <summary>
        /// 修改文章
        /// </summary>
        /// <param name="art">文章信息</param>
        /// <returns></returns>
        [HttpPost]
        [Route("update")]
        [HMACAuthenticationAttribute]
        public ApiResult UpdateArticle(Article art)
        {
            ApiResult res = new ApiResult();

            try
            {
                string user = "admin";
                Article art2 = Article.SingleOrDefault(" where ID = @0 ", art.ID);
                art2.Title = art.Title;
                art2.Content = art.Content;
                art2.IssueRange = art.IssueRange;
                art2.SpecificUser = art.SpecificUser;
                art2.remark = art.remark;
                art2.Tag = art.Tag;
                art2.SysOrder = art.SysOrder;
                art2.SysLastUpd = DateTime.Now;
                art2.SysLastUpdBy = user;
                int obj = art2.Update();

                if (obj > 0)
                {
                    res.code = HttpCode.success;
                    res.message = "修改成功";
                }
                else
                {
                    res.code = HttpCode.Mod_Failed;
                    res.message = "修改失败";
                }

            }
            catch (Exception ex)
            {
                MessageBL.Insert(new MessageBL(MessageType.Exception, "article", "修改文章错误：" + ex.Message));
                res.code = HttpCode.fail;
                res.message = ex.Message;
            }
            return res;

        }


        /// <summary>
        ///  删除文章
        /// </summary>
        /// <param name="ID">文章ID</param>
        /// <returns></returns>
        [HttpPost]
        [Route("del")]
        [HMACAuthenticationAttribute]
        public ApiResult DelArticle(string ID)
        {
            ApiResult res = new ApiResult();

            try
            {
                string user = "admin";
                int obj = Article.Update(string.Format(" set SysDeleted = 1,SysLastUpd = '{1}',SysLastUpdBy = '{2}' where ID = '{0}' ", ID, DateTime.Now, user));
                if (obj > 0)
                {
                    int i = db.Execute("DELETE FROM [dbo].[MessageAlert] WHERE ArticleID=@0",ID);
                    res.code = HttpCode.success;
                    res.message = "删除成功";
                }
                else
                {
                    res.code = HttpCode.Del_Failed;
                    res.message = "删除失败";
                }

            }
            catch (Exception ex)
            {
                MessageBL.Insert(new MessageBL(MessageType.Exception, "article", "删除文章错误：" + ex.Message));
                res.code = HttpCode.fail;
                res.message = ex.Message;
            }
            return res;
        }

        ///----------------------------------名师团队---------------------------///

        /// <summary>
        /// 获取某栏目下的文章列表
        /// </summary>
        /// <param name="code">栏目代码</param>
        /// <returns></returns>
        [HttpGet]
        [Route("list")]
        public ApiResult GetList(string code)
        {
            ApiResult res = new ApiResult();
            try
            {
                List<Article> list = db.Fetch<Article>("where SysDeleted=0 and ColumnCode=@0 order by SysOrder", code);
                res.code = HttpCode.success;
                res.message = "获取成功";
                res.data = list;
            }
            catch (Exception ex)
            {
                MessageBL.Insert(new MessageBL(MessageType.Exception, "article", "获取某栏目下的文章列表错误：" + ex.Message));
                res.code = HttpCode.fail;
                res.message = ex.Message;
            }
            return res;
        }

    }
}
